

import UIKit
import SnapKit

class Font: UIViewController {
//    定义label变量
    let label = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = "I am the king of the world"
        label.textAlignment = NSTextAlignment.center //居中
        label.font = UIFont.systemFont(ofSize: 30)
        self.view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.top.equalTo(100)
            make.centerX.equalTo(self.view)
        }
        
        let changeBtn = UIButton(type: .custom)
        changeBtn.setTitle("Change Font Family", for: .normal)
        changeBtn.addTarget(self, action: #selector(changeFontFamily), for: UIControl.Event.touchUpInside)
        changeBtn.setTitleColor(UIColor.blue, for: .normal)
        changeBtn.layer.borderColor = UIColor.blue.cgColor
        changeBtn.layer.borderWidth = 1
        changeBtn.layer.cornerRadius = 5
        self.view.addSubview(changeBtn)
        changeBtn.snp.makeConstraints { (make) in
            make.top.equalTo(500)
            make.centerX.equalTo(self.view)
            make.width.equalTo(200)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
//    修改字体
    @objc func changeFontFamily() {
        let font = getFamily();
        label.font = UIFont(name: font, size: 30)
    }
//    获取字体组
    func getFamily() -> String {
        var fontFamily = [String]();
        let familyNames = UIFont.familyNames
        for familyName in familyNames {
            let fontNames = UIFont.fontNames(forFamilyName: familyName)
            for fontName in fontNames {
               fontFamily.append(fontName)
            }
        }
        return fontFamily[random(min: 0,max: fontFamily.count)]
    }
//    生成随机数
    func random(min:Int,max:Int) -> Int {
       return Int.randomIntNumber(lower: min, upper: max)
    }
    
}

public extension Int {
    /*这是一个内置函数
     lower : 内置为 0，可根据自己要获取的随机数进行修改。
     upper : 内置为 UInt32.max 的最大值，这里防止转化越界，造成的崩溃。
     返回的结果： [lower,upper) 之间的半开半闭区间的数。
     */
    public static func randomIntNumber(lower: Int = 0,upper: Int = Int(UInt32.max)) -> Int {
        return lower + Int(arc4random_uniform(UInt32(upper - lower)))
    }
    /**
     生成某个区间的随机数
     */
    public static func randomIntNumber(range: Range<Int>) -> Int {
        return randomIntNumber(lower: range.lowerBound, upper: range.upperBound)
    }
}
